package com.example.datn.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.example.datn.R;
import com.example.datn.manager.AlbumManager;
import com.example.datn.manager.SingerManager;
import com.example.datn.manager.SongManager;
import com.example.datn.manager.UrlManager;
import com.example.datn.objects.AlbumObject;
import com.example.datn.objects.SingerOject;
import com.example.datn.objects.SongObject;
import com.example.datn.transformer.Transformer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

public class LoadResourceActivity extends Activity{

	ProgressDialog Dialog;// = new ProgressDialog(LoadResourceActivity.this);
	SingerOject singer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		singer = SingerManager.getInstance().getCurrentSinger();
		
		setContentView(R.layout.load_resources);
		Dialog = new ProgressDialog(this);
		new LoadListAlbum().execute(singer.linkGetAlbum);	
	}

	
	private class LoadListAlbum extends AsyncTask<String, Void, Void>{
		ArrayList<AlbumObject> listAlbum;
		
		@Override
		protected void onPreExecute() {			
			Dialog.setMessage("Đang tải dữ liệu..");
			Dialog.show();
			listAlbum = new ArrayList<AlbumObject>();
			super.onPreExecute();
		}			

		@Override
		protected Void doInBackground(String... params) {
			Log.d("test","start load");
			Document doc = null;
			Pattern pattern;
			Matcher matcher;
			AlbumObject album;
			try {			 
				doc = Jsoup.connect(params[0]).get();			
				Elements divs = doc.select("div");
				for (Element div : divs) {	 
					if(div.hasClass("content-item")){
						album = new AlbumObject();
						Elements links = div.select("a");
						for(Element link : links){
							pattern = Pattern.compile("/album/.*./(.+?).html");
							matcher = pattern.matcher(link.attr("href"));
							if (matcher.find()){
								album.linkPlayAlbum = UrlManager.linkMp3+link.attr("href");
								Log.d("link album", album.linkPlayAlbum);
								album.albumId = matcher.group(1);
							}							
							break;
						}
						
						Elements images = div.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
						for (Element image : images) {
							album.linkImage = image.attr("src");
							album.albumName = image.attr("alt");
							break;
						}
						
						listAlbum.add(album);
					}					
				}		 
			} catch (Exception e) {
				Log.d("sdfgh", ":::" + e.toString());
			}
			return null;
		}
		

		@Override
		protected void onPostExecute(Void result) {			
			super.onPostExecute(result);
			if(listAlbum.size() > 0)
				AlbumManager.getInstance().setListAlbum(listAlbum);
			new LoadListSong().execute(UrlManager.urlGetAllListSong);
		}
		
	}
	
	private class LoadListSong extends AsyncTask<String, Void, Void>{
		private String Content;
    	private String Error = null;      	
    	ArrayList<SongObject> listSong = new ArrayList<SongObject>();
		
		@Override
		protected void onPreExecute() {			
			super.onPreExecute();
		}		
		
		@Override
		protected Void doInBackground(String... params) {
			String songName = "", urlSong = "", albumName = "", albumId="";
			int luotNghe = 0, id = 0;
			SongObject song;
			int numbersLink = singer.listLinkSong.length;
			/************ Make Post Call To Web Server ***********/
			Document doc;
			try {
				for(int i = 0; i < numbersLink; i++){
					doc = Jsoup.connect(singer.listLinkSong[i]).get();			
					Elements links = doc.select("ul");
					for (Element link : links) {				 
						if(link.hasClass("song-list")){				
							Elements divs = link.select("li");
							for (Element div : divs) {
								Elements as = div.select("a");
								for (Element a : as) {
									if(a.hasClass("_strCut")){
										if(a.attr("strlength").equals("35")){
											songName = a.text();
											urlSong = "http://mp3.zing.vn" + a.attr("href");										
										}									
										else{											
											Pattern pattern = Pattern.compile("/album/.*./(.+?).html");
											Matcher matcher = pattern.matcher(a.attr("href"));
											if (matcher.find()){
												albumId = matcher.group(1);
											}
											albumName = a.text();
										}
									}																			
								}
								song = new SongObject();
								++id;
								song.songNo = id;	
								song.albumId = albumId;
								song.songName = songName;
								song.urlSong = urlSong;
								song.albumName = albumName;
								listSong.add(song);
							}
							break;
						}	
					}
				}							
			} catch (IOException e) {		
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Transformer transform = new Transformer();
			Dialog.dismiss();
            if (Error != null) {                  
            	  Toast.makeText(getApplicationContext(), "Loi ket noi, xin hay kiem tra lai ket noi mang cua ban",  
            			  Toast.LENGTH_LONG).show();             	
            } else {            
				SongManager.getInstance().setListSong(listSong);
            }
            Log.d("test","finish load");
            Intent i = new Intent(LoadResourceActivity.this, SongsViewActivity.class);
        	startActivity(i);        	
        	finish();
		}
	}
	
}
